package com.ming.mallchat.common.common.exception;

import com.ming.mallchat.common.common.domain.vo.resp.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandle {

    /**
     * 字段校验错误异常
     * @param e
     * @return {@link ApiResult}<{@link ?}>
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    private ApiResult<?> methodArgumentNotValidException(MethodArgumentNotValidException e) {
        StringBuilder errorBuilder = new StringBuilder();
        e.getBindingResult().getFieldErrors().forEach(x ->
                errorBuilder.append(x.getField()).append(x.getDefaultMessage()).append(","));
        String errorMsg = errorBuilder.substring(0, errorBuilder.length() - 1);
        log.info("methodArgumentNotValid exception! The reason is:{}",e.getMessage(),e);
        return ApiResult.fail(CommonErrorEnum.PARAM_INVALID.getCode(), errorMsg);
    }

    /**
     * 自定义业务异常
     * @param e
     * @return {@link ApiResult}<{@link ?}>
     */
    @ExceptionHandler(value = BusinessException.class)
    private ApiResult<?> businessException(BusinessException e){
        log.info("business exception! The reason is:{}",e.getMessage(),e);
        return ApiResult.fail(e.getErrorCode(),e.getErrorMsg());
    }

    /**
     * 兜底全局异常处理
     * @param e
     * @return {@link ApiResult}<{@link ?}>
     */
    @ExceptionHandler(value = Throwable.class)
    private ApiResult<?> throwable(Throwable e){
        log.error("system exception! The reason is:{}",e.getMessage(),e);
        return ApiResult.fail(CommonErrorEnum.SYSTEM_ERROR);
    }

}
